package com.ywb.order.controller;

import com.ywb.common.entity.*;
import com.ywb.order.lb.LoadBalancer;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author ywb
 */
@RestController
public class OrderController {
    public static final String PAYMENT_URL = "http://PAYMENT-SERVICE8001";

//    服务发现
    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private LoadBalancer loadBanlancer;

    @Resource
    private RestTemplate restTemplate;


    @GetMapping("/payment/{id}")
    public Result getPayment(@PathVariable String id){
        Result result = restTemplate.getForObject(PAYMENT_URL + "/payment/" + id, Result.class);
        return result;
    }

    @GetMapping("/payment")
    public Result insert(Payment payment){
        return restTemplate.postForObject(PAYMENT_URL, payment, Result.class);
    }
    @GetMapping("/lb")
    public String lb(){
        List<ServiceInstance> instances = discoveryClient.getInstances("payment-com.ywb.payment.service");
        ServiceInstance serviceInstance = loadBanlancer.getServiceInstance(instances);
        String uri = serviceInstance.getUri().toString();
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(uri + "/payment/lb", String.class);
        return responseEntity.getBody();
    }
}
